package cn.edu.ustc.brainor.ustcgate;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;

/**
 * Created by Brainor on 2016/10/13.
 */

public class LocationAcquire {

    public Context context;
    private static LocationAcquire mInstance;
    private LocationManager locationManager;
    private MyLocationListener listener;

    public static LocationAcquire getmInstance(Context context) {
        //确保只有一个实例
        if (mInstance == null) {
            mInstance = new LocationAcquire(context);
        }
        mInstance.context = context;
        return mInstance;

    }

    private LocationAcquire(Context context) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    /**
     * 开始进行地址数据记录
     */
    public void startLocationChangeListenner() {
        Criteria criteria = new Criteria();
//        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//不要求精确定位
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setSpeedRequired(false);
        String provider = locationManager.getBestProvider(criteria, true);
        try {
            locationManager.requestLocationUpdates(provider, 60*1000, 0, getListener());//数字待改
        } catch (SecurityException e) {
            //取消minstance
        }
    }

    private MyLocationListener getListener() {
        if (listener == null) {
            listener = new MyLocationListener();
        }
        return listener;
//确保只有一个listener
    }

    private final class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            //发送邮件部分
            String[] 位置 = {String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), String.valueOf(location.getAccuracy())};
            ((Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(400);
            new Mail().execute(位置);

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {
            startLocationChangeListenner();
        }
    }
    public void stopLocationChangeListener(){
        try {
            locationManager.removeUpdates(getListener());
        }catch (SecurityException e){

        }
    }
}
